﻿using Microsoft.AspNetCore.Mvc;

namespace RuoVea.Swms.Server.Service
{
    /// <summary>
    /// 产品管理
    /// </summary>
    [ApiExplorerSettings(GroupName = "swms")]
    public class ProductService : IApplicationService
    {
        private readonly SugarRepository<WmsProduct> _productRepo;
        private readonly SugarRepository<WmsStockIn> _stockInRepo;
        private readonly SugarRepository<WmsStockOut> _stockOutRepo;
        private readonly SugarRepository<WmsCategory> _categoryRepo;
        private readonly SugarRepository<WmsLocation> _locationRepo;
        private readonly LocationService _storageLocationService;
        private readonly ICurrentUser _currentUser;

        public ProductService(
            SugarRepository<WmsProduct> productRepo,
            SugarRepository<WmsStockIn> stockInRepo,
            SugarRepository<WmsStockOut> stockOutRepo,
            SugarRepository<WmsCategory> categoryRepo,
            SugarRepository<WmsLocation> locationRepo, 
            ICurrentUser currentUser,
            LocationService storageLocationService)
        {
            _productRepo = productRepo;
            _stockInRepo = stockInRepo;
            _stockOutRepo = stockOutRepo;
            _categoryRepo = categoryRepo;
            _locationRepo = locationRepo;
            _currentUser = currentUser;
            _storageLocationService = storageLocationService;
        }

        /// <summary>
        /// 获取产品分页列表
        /// </summary>
        public async Task<RestfulResult<PageResult<WmsProduct>>> GetPagesAsync(ProductPageParam data)
        {
            var restful = new RestfulResult<PageResult<WmsProduct>>() { Code = CodeStatus.OK };
            data ??= new ProductPageParam { PageNo = 1, PageSize = 10 };

            var query = await _productRepo.AsQueryable()
                .WhereIF(data.CategoryId > 0, u => u.Category.Id == data.CategoryId)
                .WhereIF(!string.IsNullOrEmpty(data.Keyword), u => u.ProductName.Contains(data.Keyword) || u.Code.Contains(data.Keyword))
                .Includes(u => u.Category)
                .Includes(u => u.Location)
                .ToPageAsync(data.PageNo, data.PageSize);

            restful.Data = query;
            return restful;
        }
        /// <summary>
        /// 获取所有位置列表（用于下拉选择）
        /// </summary>
        public async Task<RestfulResult<List<WmsProduct>>> GetlistAsync()
        {
            var restful = new RestfulResult<List<WmsProduct>> { Code = CodeStatus.OK };
            var locations = await _productRepo.GetListAsync();
            restful.Data = locations;
            return restful;
        }
        /// <summary>
        /// 添加新产品
        /// </summary>
        [UnitOfWork]
        public async Task<RestfulResult> AddAsync(WmsProduct data)
        {
            var restful = new RestfulResult() { Code = CodeStatus.BadRequest };

            // 验证产品编码唯一性
            var exists = await _productRepo.IsAnyAsync(u => u.Code == data.Code);
            if (exists)
            {
                restful.Message = "产品编码已存在";
                return restful;
            }

            // 验证类别是否存在
            if (data.CategoryId > 0)
            {
                var categoryExists = await _categoryRepo.IsAnyAsync(u => u.Id == data.CategoryId);
                if (!categoryExists)
                {
                    restful.Message = "产品类别不存在";
                    return restful;
                }
            }

            // 验证位置是否存在
            if (data.LocationId > 0)
            {
                var locationExists = await _locationRepo.IsAnyAsync(u => u.Id == data.LocationId);
                if (!locationExists)
                {
                    restful.Message = "存放位置不存在";
                    return restful;
                }
            }

            data.Creator = _currentUser.UserId;
            data.CurrentStock = data.InitialStock;

            var result =await _productRepo.Context.Ado.UseTranAsync(async () => 
            {
                bool result1 = await _productRepo.InsertAsync(data);
                if (result1 && data.LocationId > 0)
                {
                    // 更新位置容量
                    await _storageLocationService.UpdateLocationCapacity(data.LocationId, data.InitialStock);
                }
            });
            

            restful.Data = result.IsSuccess;
            restful.Code = result.IsSuccess ? CodeStatus.OK : CodeStatus.BadRequest;
            restful.Message = result.IsSuccess ? "添加成功" : result.ErrorMessage;
            return restful;
        }

        /// <summary>
        /// 更新产品信息
        /// </summary>
        public async Task<RestfulResult> UpdateAsync(WmsProduct data)
        {
            var restful = new RestfulResult() { Code = CodeStatus.BadRequest };

            var exists = await _productRepo.IsAnyAsync(u => u.Id == data.Id);
            if (!exists)
            {
                restful.Message = "产品不存在";
                return restful;
            }

            // 保留原始库存数量
            var originalProduct = await _productRepo.GetByIdAsync(data.Id);
            data.CurrentStock = originalProduct.CurrentStock;
            data.InitialStock = originalProduct.InitialStock;

            bool result = await _productRepo.UpdateAsync(data);
            restful.Data = result;
            restful.Code = result ? CodeStatus.OK : CodeStatus.BadRequest;
            restful.Message = result ? "更新成功" : "更新失败";
            return restful;
        }

        /// <summary>
        /// 删除产品
        /// </summary>
        public async Task<RestfulResult> DeleteAsync(EntityBaseId data)
        {
            var restful = new RestfulResult() { Code = CodeStatus.BadRequest };

            // 检查产品是否存在
            var product = await _productRepo.GetByIdAsync(data.Id);
            if (product == null)
            {
                restful.Message = "产品不存在";
                return restful;
            }

            if (product.CurrentStock > 0)
            {
                restful.Message = "产品仍有库存，不能删除";
                return restful;
            }

            // 检查是否有出入库记录
            var hasRecords = await _stockInRepo.IsAnyAsync(u => u.ProductId == product.Id) ||
                            await _stockOutRepo.IsAnyAsync(u => u.ProductId == product.Id);

            if (hasRecords)
            {
                restful.Message = "产品有出入库记录，不能删除";
                return restful;
            }

            bool result = await _productRepo.DeleteByIdAsync(data.Id);
            restful.Data = result;
            restful.Code = result ? CodeStatus.OK : CodeStatus.BadRequest;
            restful.Message = result ? "删除成功" : "删除失败";
            return restful;
        }

        /// <summary>
        /// 获取产品类别列表
        /// </summary>
        public async Task<RestfulResult<List<WmsCategory>>> GetCategoriesAsync()
        {
            var restful = new RestfulResult<List<WmsCategory>> { Code = CodeStatus.OK };
            var categories = await _productRepo.AsQueryable()
                .GroupBy(u => u.Category)
                .Select(u => u.Category)
                .ToListAsync();
            restful.Data = categories;
            return restful;
        }
    }
}